<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/5/22
 * Time: 18:04
 */
namespace App\Http\Controllers\Api\User;

use App\Http\Controllers\Api\WeChatControllerBase;
use App\Http\Controllers\Controller;
use App\Modules\System\Services\DictionaryService;
use App\Modules\User\Services\UserService;
use App\Modules\User\Services\UserTaskDetailService;
use App\Modules\Index\Models\SetMedicinal;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

use Illuminate\Support\Facades\Log;
use Hashids;

class UserController extends Controller {
    /**
     * 同意用户服务协议
     * @param Request $request
     */
    public function service_protoc(Request $request) {
        $uid = $this->getLoginUserId();
        $user_info = UserService::getById($uid);
        $user_info->is_agree_protoc =1;
        $user_info->save();
    }

    /**
     * 绑定手机号
     * @param Request $request
     * @return mixed
     */
    public function bind_phone(Request $request) {
        $session_key = $request->input('session_key','');
        $encryptedData = $request->input('encrypted_data','');
        $iv = $request->input('iv','');
        $app =WeChatControllerBase::initInstance();
        $decryptedData = $app->encryptor->decryptData($session_key, $iv, $encryptedData);
        if(empty($decryptedData)||!isset($decryptedData['phoneNumber'])||empty($decryptedData['phoneNumber'])) {
            return response()->error('DECRYPT_FAIL');
        }
        $phone = $decryptedData['phoneNumber'];
        $uid = $this->getLoginUserId();
        if(empty($phone)) {
            return response()->error('PARAM_EMPTY');
        }
        $user_info_by_uid = UserService::getById($uid);
        $user_info_by_phone = UserService::getUserInfoByPhone($phone);
        \DB::beginTransaction();
        try{
            if($user_info_by_phone && ($user_info_by_phone->id != $uid)) {
                UserService::deleteOne($uid);
                $user_info_by_phone->openid = $user_info_by_uid->openid;
                $user_info_by_phone->target_value = DictionaryService::getDictionary('target')->value;
                $user_info_by_phone->save();
            }else{
                $user_info_by_uid->phone = $phone;
                $user_info_by_uid->target_value = DictionaryService::getDictionary('target')->value;
                $user_info_by_uid->save();
            }
            \DB::commit();
        }catch (\Exception $e) {
            \Log::error(__FUNCTION__.$uid.$e->getMessage());
            \DB::rollback();
            return response()->error('BIND_ERROR');
        }
        return response()->success();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function getUserProfile(Request $request) {
        $uid = $this->getLoginUserId();
        $user_info = UserService::getById($uid);
        if($user_info && $user_info->phone) {
            $user_info->is_bind_phone = 1;
        }else if($user_info){
            $user_info->is_bind_phone = 0;
        }
        //unset($user_info->id);
        $user_info->sid = \Hashids::encode($user_info->id);
        $private_key = md5($user_info->sid.env('INSIGHT_USER_SIGN'));
        $user_info->sign = $private_key;
        $medicinal = SetMedicinal::getMedicinal($user_info->id);
        $user_info->user_medicinal = empty($medicinal) ? 0 : 1;
        $user_info->nickname = !empty($user_info->nickname) ? $user_info->nickname : $user_info->phone;
        unset($user_info->id);
        unset($user_info->phone);
        if ( !empty($user_info->avatar) && !preg_match('/http[s]*:\/\//',$user_info->avatar) ) {
            $user_info->avatar = env('APP_DOMAIN').$user_info->avatar;
        }
        return response()->success($user_info);
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function setHeightOrWeight(Request $request) {
        $uid = $this->getLoginUserId();
        $height = $request->input('height','');
        $weight = $request->input('weight','');
        if(empty($height) && empty($weight)) {
            return response()->error('PARAM_EMPTY');
        }
        $user_info = UserService::getById($uid);
        if($height) {
            $user_info->height = $height;
        }
        if($weight) {
            $user_info->weight = $weight;
        }
        $user_info->save();
        return response()->success();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function getWechatUserInfo(Request $request) {
        $user_info = $request->input('userInfo','');
        $user_info = json_decode($user_info,true);
        $uid = $this->getLoginUserId();
        $user = UserService::getById($uid);
        $user->nickname = $user_info['nickName'];
        $user->avatar = $user_info['avatarUrl'];
        $user->save();
        return response()->success();
    }

    /**
     * 批量上传图片到服务器
     * @param Request $request
     * @return mixed
     */
    public function upload_img(Request $request) {
        $imgs = $request->allFiles();
        $imgs_return = array();
        foreach ($imgs as $img) {
            $path = '/upload';
            $file_name = date("YmdHis",time()).rand(1000,9999).".png";
            $path_ret=$path.'/'.$file_name;
            $img_path = public_path().$path_ret;

            $path_=$img->storeAs('upload',$file_name,'public');
            $imgs_return[] = $path_ret;

        }
        return response()->success($imgs_return);
    }
}